package com.flywen.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.drew.imaging.ImageProcessingException;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.imaging.mp4.Mp4MetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.ParseException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

/**
 * Create: 2023-06-16 15:09<br/>
 * Author MR.W <br/>
 * Version: 1.0 <br/>
 * Description: 图片工具类<br/>
 */
public class PhoneFileUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(PhoneFileUtils.class);

    /**
     * 文件夹绝对路径
     * @param basePath
     */
    public static void rename(String basePath){

        List<File> files = FileUtil.loopFiles(basePath);
        long start = System.currentTimeMillis();
        for (File file : files) {
            String newName = getNewNameByCreateTime(file);
            if (StringUtils.isBlank(newName)){
            }
            String absolutePath = file.getAbsolutePath();
            int i1 = absolutePath.lastIndexOf(".");
            int i = absolutePath.lastIndexOf("\\");
            String path = absolutePath.substring(0, i);
            String rename = path+File.separator+ newName;
            File dest = new File(rename);
            if (!dest.exists()){
                file.renameTo(dest);
            }
        }
        long finish = System.currentTimeMillis();
        LOGGER.info("重命名结束! 耗时:{}", (finish -start));
    }


    /**
     * 根据创建时间获取最新文件名
     * @param file
     * @return
     */
    public static String getNewNameByCreateTime(File file) {
        String result = null;
        Metadata metadata;
        String fileType = "";
        try {
            if (file.getName().endsWith("mp4") || file.getName().endsWith("MP4")){

                metadata = Mp4MetadataReader.readMetadata(file);
                fileType= "mp4";
            }else if (file.getName().endsWith("jpg") || file.getName().endsWith("JPG")){

                metadata = JpegMetadataReader.readMetadata(file);
                fileType = "jpg";
            }else{
                LOGGER.info("{} 暂不支持",file.getName());
                return result;
            }
            Iterator<Directory> it = metadata.getDirectories().iterator();
            while (it.hasNext()) {
                Directory exif = it.next();
                Iterator<Tag> tags = exif.getTags().iterator();
                while (tags.hasNext()) {
                    Tag tag = tags.next();
                    String tagName = tag.getTagName();

                    String tagStr = tag.toString();

                    if (fileType.equalsIgnoreCase("mp4")){
                        if (tagName.contains("Creation Time")){
                            String[] split = tagStr.split("-");
                            if (split.length > 1){
                                String createTime = split[1].trim();
                                Date date = DateUtils.parseDate(createTime, Locale.US, "EEE MMM dd HH:mm:ss zzz yyyy");
                                return DateUtil.format(date,"yyyyMMddHHmmss")+"."+fileType;

                            }
                        }
                    }else if (fileType.equalsIgnoreCase("jpg")){
                        if (tagName.contains("Date/Time Original")){
                            String[] split = tagStr.split("-");
                            if (split.length > 1){
                                String createTime = split[1].trim();
                                Date date = DateUtils.parseDate(createTime,"yyyy:MM:dd HH:mm:ss");
                                return DateUtil.format(date,"yyyyMMddHHmmss")+"."+fileType;
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ImageProcessingException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return result;
    }


    /**
     * 获取文件的创建时间
     * @param file
     * @return
     */
    public static Date getCreateTime(File file) {
        Date result = null;
        Metadata metadata;
        String fileType = "";
        try {
            if (file.getName().endsWith("mp4") || file.getName().endsWith("MP4")){

                metadata = Mp4MetadataReader.readMetadata(file);
                fileType= "mp4";
            }else if (file.getName().endsWith("jpg") || file.getName().endsWith("JPG")){

                metadata = JpegMetadataReader.readMetadata(file);
                fileType = "jpg";
            }else{
                LOGGER.info("{} 暂不支持",file.getName());
                return result;
            }
            Iterator<Directory> it = metadata.getDirectories().iterator();
            while (it.hasNext()) {
                Directory exif = it.next();
                Iterator<Tag> tags = exif.getTags().iterator();
                while (tags.hasNext()) {
                    Tag tag = tags.next();
                    String tagName = tag.getTagName();

                    String tagStr = tag.toString();

                    if (fileType.equalsIgnoreCase("mp4")){
                        if (tagName.contains("Creation Time")){
                            String[] split = tagStr.split("-");
                            if (split.length > 1){
                                String createTime = split[1].trim();
                                result = DateUtils.parseDate(createTime, Locale.US, "EEE MMM dd HH:mm:ss zzz yyyy");
                            }
                        }
                    }else if (fileType.equalsIgnoreCase("jpg")){
                        if (tagName.contains("Date/Time Original")){
                            String[] split = tagStr.split("-");
                            if (split.length > 1){
                                String createTime = split[1].trim();
                                result = DateUtils.parseDate(createTime,"yyyy:MM:dd HH:mm:ss");
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ImageProcessingException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return result;
    }



    /**
     * 处理 单张 图片
     *
     * @return void
     * @date 2015-7-25 下午7:30:47
     */
    public static Date getImageTime(File jpegFile) {
        Date result = null;
        if (!(jpegFile.getName().endsWith("jpg") || jpegFile.getName().endsWith("JPG"))){

            //System.out.println("暂不支持！"+jpegFile.getName());
            return result;
        }
        Metadata metadata;
        try {
            metadata = JpegMetadataReader.readMetadata(jpegFile);
            Iterator<Directory> it = metadata.getDirectories().iterator();
            while (it.hasNext()) {
                Directory exif = it.next();
                Iterator<Tag> tags = exif.getTags().iterator();
                while (tags.hasNext()) {
                    Tag tag = (Tag) tags.next();
                    String tagName = tag.getTagName();

                    String tagStr = tag.toString();
                    System.out.println(tagName+"---->"+ tagStr);
                    if (tagName.contains("Date/Time Original")){
                        String[] split = tagStr.split("-");
                        if (split.length > 1){
                            String createTime = split[1].trim();
//                            System.out.println(tagName+"---->"+ createTime);
                            result = DateUtils.parseDate(createTime,"yyyy:MM:dd HH:mm:ss");
//                            System.out.println(tagName+"---->"+ result);
                            break;
                        }
                    }
                }
            }
        } catch (JpegProcessingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return result;
    }



    /**
     * 获取照片创建日期
     * @param file
     * @return
     */
    public static String getCreationTime(File file) {

        BasicFileAttributes attr = null;
        try {
            Path path = file.toPath();
            attr = Files.readAttributes(path, BasicFileAttributes.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建时间
        Instant instant = attr.creationTime().toInstant();
        // 更新时间
//        Instant instant = attr.lastModifiedTime().toInstant();
        // 上次访问时间
//        Instant instant = attr.lastAccessTime().toInstant();
        String format = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneId.systemDefault()).format(instant);
        return format;
    }
    // ======================================================================
    // 另一种方法
    private static Long getFileCreateTime(String filePath) {
        File file = new File(filePath);
        try {
            Path path = Paths.get(filePath);
            BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
            BasicFileAttributes attr = basicview.readAttributes();
            Long lastModified = file.lastModified();
            return attr.creationTime().toMillis();
        } catch (Exception e) {
            e.printStackTrace();
            return file.lastModified();
        }
    }


}
